package com.gome.ai.aiparter.ws.test;


import com.gome.ai.aiparter.ws.AIConfig;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;

@Slf4j
public class AIWorker extends WebSocketClient {

	public AIWorker(URI serverUri) {
		super(serverUri);
	}

	public static void main(String[] args) throws URISyntaxException {
		URI uri = new URI("ws://127.0.0.1:11720/ws/9f135773-1274-40a4-a863-1ca7fcd50943");
		new AIWorker(uri).connect();
//		while (true){
//			try {
//				new AIWorker(uri).connect();
//			}catch (Exception e){
//				log.error("创建连接失败,3s后重试:{}",uri,e);
//			}
//
//			try {
//				Thread.sleep(3000);
//			} catch (InterruptedException e) {
//				throw new RuntimeException(e);
//			}
//		}
	}

	int index = 0;

	@Override
	public void onOpen(ServerHandshake serverHandshake) {
		new Thread(() -> {
			calc();
			send("end");
		}).start();
	}

	@Override
	public void onMessage(String s) {
		new Thread(() -> {
			try {
				calc();
				String notice = "This sentence consists of the following words:\n\r";
				send(notice);

				String[] arr = s.split(" ");
				for (String text : arr) {
					calc();
					send(text + "\n\r");
				}
			}catch (Exception e){
				//nothing
			}finally {
				send("end");
			}

		}).start();
	}

	@Override
	public void send(String text) {
		super.send(text);
		log.info("send:{}",text);
	}

	private void calc(){
		try {
			Thread.sleep((long) (Math.random() * 300));
		} catch (InterruptedException e) {
			//nothing
		}

	}

	@Override
	public void onClose(int i, String s, boolean b) {
		log.info("客户端关闭");
	}

	@Override
	public void onError(Exception e) {
		log.warn("客户端发送错误",e);
		close();
	}
}
